/*
 * @Author: yangzonglong
 * @Date: 2021-03-05 12:08:36
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-31 09:40:47
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Picker } from 'antd-mobile';
import Icon from './icon/Icon';
import RequiredMark from './RequiredMark';
import { getSource } from '../api';

let timeId = null;

const divStyle = {
  border: '1px solid rgba(35, 37, 40, 0.1)',
  padding: '12px 14px',
  fontSize: '14px',
  height: ' 45px',
  position: 'relative',
  lineHeight: '19px',
};

const iconStyle = {
  position: 'absolute',
  right: '15px',
  fontSize: '14px',
};

// 获取条件
const getQuery = (screenCondition, screenConditionRules, sendData) => {
  let obj = { $or: [] };
  let _temp = {};
  sendData = sendData || {};
  screenCondition.forEach((item) => {
    item.dataSource.forEach((ele) => {
      _temp[ele.field] =
        ele.condition !== 'equal'
          ? {
              [ele.condition]: ele.condition === '$ne' || ele.condition === '$like' ? ele.keyword : [ele.keyword],
            }
          : ele.keyword;
    });
  });

  if (sendData?.id) {
    screenConditionRules = screenConditionRules || [];

    screenConditionRules.forEach((item) => {
      item.dataSource.forEach((ele) => {
        _temp[ele.field] =
          ele.condition !== 'equal'
            ? {
                [ele.condition]: ele.condition === '$ne' || ele.condition === '$like' ? sendData[ele.keyword] : [sendData[ele.keyword]],
              }
            : sendData[ele.keyword];
      });
    });
  }

  obj.$or.push(_temp);

  return !screenCondition?.length && !sendData ? {} : { where: obj };
};

const App = (props, ref) => {
  const { disabled, formItemProps, inputProps, sendData } = props;
  const [value, setValue] = useState(undefined);
  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    if (timeId) {
      clearTimeout(timeId);
      timeId = null;
    }
    timeId = setTimeout(() => {
      getSource(
        inputProps.serviceType === 'APP' ? `/bk/api/${inputProps.serviceModuleCode}/${inputProps.modulesName}/find` : inputProps.modulesUrl,
        getQuery(inputProps.screenCondition, inputProps.screenConditionRules, sendData)
      ).then((res) => {
        setDataSource(
          (res.rows || []).map((item) => ({
            value: item[inputProps?.filedShowName],
            label: item[inputProps?.showFieldName],
          }))
        );
        timeId = null;
      });
    }, 200);
  }, [inputProps, sendData]);

  useEffect(() => {
    setValue(props.initialValue);
  }, [props]);

  useImperativeHandle(ref, () => ({
    getData: () => value,
  }));

  return (
    <Picker data={dataSource} disabled={disabled} cols={1} value={value} onOk={setValue}>
      <div className="am-list-item am-input-item am-list-item-middle">
        <div className="am-list-line">
          <div className="am-input-label am-input-label-5">
            {
              <span>
                {formItemProps?.required && <RequiredMark />}
                {formItemProps?.label}
              </span>
            }
          </div>
          <div style={divStyle}>
            {value ? (
              dataSource.filter((item) => item.value === value?.[0] || item.value === value)?.[0]?.label || ''
            ) : (
              <span style={{ color: '#bbb' }}>{inputProps?.placeholder || ''}</span>
            )}

            {value ? (
              <Icon
                onClick={(e) => {
                  e.stopPropagation();
                  setValue(undefined);
                }}
                icon="&#xe645;"
                style={{ ...iconStyle, zIndex: 999 }}
              />
            ) : (
              <Icon icon="&#xe669;" style={iconStyle} />
            )}
          </div>
        </div>
      </div>
    </Picker>
  );
};

export default forwardRef(App);
